<template>
  <div class="chat">
    <van-sticky>
      <van-nav-bar left-arrow @click-left="$router.back()">
        <template #title>
          {{ name }}
        </template>
        <template #left>
          <van-icon name="arrow-left" size="18" color="black" />
        </template>
      </van-nav-bar>
    </van-sticky>

    <div class="chat-content">
      <div
        v-for="(item, index) in lisList"
        :key="index"
        @mousedown="startTimer"
        @mouseup="endTimer"
        class="chat-item"
      >
        <div
          :key="index"
          :class="item.senderId == uid ? 'chat-item-right' : 'chat-item-left'"
        >
          <div
            v-if="item.senderId == uid"
            :class="item.senderId == uid ? 'chat-item-right' : 'chat-item-left'"
          >
            <!-- 图片 -->
            <span v-if="item.type == 'image'" style="padding: 0px;">
              <img
                :src="item.payload.url"
                style="width: 150px;"
                @click="openPreview(item.payload.url)"
                alt=""
              />
              <van-overlay
                :show="preview.show"
                @click="preview.show = false"
                style="z-index: 200"
              >
                <img
                  :src="preview.url"
                  style="
                    max-width: 100%;
                    max-height: 90vh;
                    position: absolute;
                    left: 50%;
                    top: 50%;
                    transform: translate(-50%, -50%);
                  "
                />
              </van-overlay>
            </span>
            <!-- 视频 -->
            <span v-else-if="item.type == 'video'" style="padding: 0px;">
              <video
                :src="item.payload.video.url"
                controls
                style="width: 150px; padding: 0px -10px;"
                alt=""
              />
            </span>
            <!-- 文字 -->
            <span v-else>{{ item.payload.text }}</span>
            <!-- 头像 -->
            <img class="chat-item-img" :src="image" width="50px" alt="" />
          </div>
          <div
            v-else
            :class="item.senderId == uid ? 'chat-item-right' : 'chat-item-left'"
          >
            <!-- 头像 -->
            <img class="chat-item-img" :src="img" width="50px" alt="" />
            <!-- 图片 -->
            <span v-if="item.type == 'image'" style="padding: 0px;">
              <img
                :src="item.payload.url"
                style="width: 150px"
                @click="openPreview(item.payload.url)"
                alt=""
              />
              <van-overlay
                :show="preview.show"
                @click="preview.show = false"
                style="z-index: 200"
              >
                <img
                  :src="preview.url"
                  style="
                    max-width: 100%;
                    max-height: 90vh;
                    position: absolute;
                    left: 50%;
                    top: 50%;
                    transform: translate(-50%, -50%);
                  "
                />
              </van-overlay>
            </span>
            <!-- 视频 -->
            <span v-else-if="item.type == 'video'" style="padding: 0px;">
              <video
                :src="item.payload.video.url"
                controls
                style="width: 150px"
                alt=""
              />
            </span>
            <!-- 文字 -->
            <span v-else>{{ item.payload.text }}</span>
          </div>
        </div>
      </div>
    </div>


      <div class="chat-input-container">
        <input
          type="text"
          class="chat-input"
          v-model="history.message"
          @keyup.enter="send()"
          placeholder="发消息..."
        />
        <button class="microphone-btn">
          <van-icon name="smile-o" />
        </button>
        <button class="smile-btn" @click="show = true">
          <van-icon name="add-o" />
        </button>
        <button class="send-btn" @click="send()">发送</button>
      </div>

  </div>
  <!-- 弹出图片与视频框 -->
  <van-overlay :show="show" @click="show = false" style="z-index: 200">
    <div class="wrapper">
      <div class="block">
        <label for="file-Image" class="file-item">上传照片</label>
        <input type="file" id="file-Image" @change="sendImageMessage" />
        <label for="file-Video" class="file-item">上传视频</label>
        <input
          type="file"
          id="file-Video"
          @change="sendVideoMessage"
          accept="video/mp4"
        />
      </div>
    </div>
  </van-overlay>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { useRoute } from "vue-router";
import goeasy from "./goeasy";
import axios from "../../../utils/axios";
const route = useRoute();
const name = route.params.name;
// 聊天用户id
const id = route.params.id;
const img = route.params.img;
console.log(img);
// 登录用户id
const uid = localStorage.getItem("_id");
const image = localStorage.getItem("img");

const show = ref(false);

// 图片预览
const preview = ref({
  show: false,
  url: "",
});

const openPreview = (url) => {
  preview.value.url = url;
  preview.value.show = true;
};

var im = goeasy.im;
let history = reactive({
  message: [],
});

let lisList = ref([]);

//建立连接
const Connect = () => {
  goeasy.connect({
    id: uid, //im必填，最大长度60字符
    data: { avatar: "/www/xxx.png", nickname: "Neo" }, //必须是一个对象，im必填，最大长度300字符，显示在会话列表中
    onSuccess: function () {
      History();
      //连接成功
      console.log("连接成功"); //连接成功
      im.on(goeasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, onPrivateMessageReceived);
    },
    onFailed: function (error) {
      //连接失败
      console.log("连接失败", error);
    },
    onProgress: function (attempts) {
      //连接或自动重连中
      console.log("连接或自动重连中", attempts);
    },
  });
};
// 图片
const sendImageMessage = (ev) => {
  var im = goeasy.im;
  let textMessage = im.createImageMessage({
    file: ev.target.files[0], //H5获得的图片file对象，Uniapp和小程序调用chooseImage，success时得到的res.tempFiles数组中的元素，比如res.tempFiles[0]即为选择的第一张图片
    to: {
      type: goeasy.IM_SCENE.PRIVATE, //私聊还是群聊，群聊为GoEasy.IM_SCENE.GROUP
      id: id,
      data: { avatar: "../../public/123.png", nickname: "Neo" }, //好友扩展数据, 任意格式的字符串或者对象，用于更新会话列表conversation.data
    },
    onProgress: function (event) {
      // console.log('file uploading:', event)
    }, //获取上传进度
  });
  im.sendMessage({
    message: textMessage,
    onSuccess: function (message) {
      //发送成功
      console.log("成功返回的数据", message);
      History();
      send();
    },
  });
};
// 视频
const sendVideoMessage = (ev) => {
  var im = goeasy.im;
  let textMessage = im.createVideoMessage({
    file: ev.target.files[0], //H5获得的图片file对象，Uniapp和小程序调用chooseImage，success时得到的res.tempFiles数组中的元素，比如res.tempFiles[0]即为选择的第一张图片
    to: {
      type: goeasy.IM_SCENE.PRIVATE, //私聊还是群聊，群聊为GoEasy.IM_SCENE.GROUP
      id: id,
      data: { avatar: "../../public/123.png", nickname: "Neo" }, //好友扩展数据, 任意格式的字符串或者对象，用于更新会话列表conversation.data
    },
    onProgress: function (event) {
      console.log("file uploading:", event);
    }, //获取上传进度
  });
  im.sendMessage({
    message: textMessage,
    onSuccess: function (message) {
      //发送成功
      console.log("成功返回的数据", message);
      History();
      send();
    },
  });
};

const sendMassage = () => {
  //创建消息, 内容最长不超过3K，可以发送字符串，对象和json格式字符串
  let textMessage = im.createTextMessage({
    text: history.message, //消息内容
    to: {
      type: goeasy.IM_SCENE.PRIVATE, //私聊还是群聊，群聊为GoEasy.IM_SCENE.GROUP
      id: id, //接收方用户id
      data: { avatar: "/www/xxx.png", nickname: "Neo" }, //接收方用户扩展数据, 任意格式的字符串或者对象，用于更新会话列表conversation.data
    },
  });
  //发送消息
  im.sendMessage({
    message: textMessage,
    onSuccess: function (message) { //发送成功
      onPrivateMessageReceived();
    },
  });
};

const send = () => {
  sendMassage();
  history.message = "";
  im.on(goeasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, onPrivateMessageReceived);
};

const History = () => {
  //获取历史记录
  im.history({
    id: id, //用户id或者群id
    type: goeasy.IM_SCENE.PRIVATE, //群聊：GoEasy.IM_SCENE.GROUP, 客服：GoEasy.IM_SCENE.CS,
    limit: 20, //可选项，返回的消息条数，默认为10条，最多30条
    onSuccess: function (result) { //成功的
      console.log("1111111", result.content);
      lisList.value = result.content;
    },
  });
};

var onPrivateMessageReceived = () => {
  History();
};
onMounted(() => {
  Connect();
  History();
  im.on(goeasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, onPrivateMessageReceived);
});
</script>

<style lang="scss" scoped>
.chat {
  margin: 0 10px;
  background-color: #f7f7f7;
}
// 聊天内容样式
.chat-content{
  width: 100%;
  height: 85vh;
  flex-direction: column;
  margin-bottom: 20px;
  overflow: scroll;
}
// 上传图片视频按钮样式
.block input[type="file"] {
  width: 90%;
  cursor: pointer;
  padding: 10px;
  background-color: #f7f7f7;
  border: 1px solid #ccc;
  border-radius: 5px;
  color: #333;
}

.block input[type="file"]::file-selector-button {
  padding: 5px 10px;
  background-color: #50abff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-right: 5px;
}

.block input[type="file"]::file-selector-button:hover {
  background-color: #4091db;
}
// 相册视频弹出框
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.block {
  width: 90%;
  height: 200px;
  background-color: #fff;
  .file-item {
    margin: 10px;
  }
}
.chat-menus {
  display: none;
}
.chat-menu {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 150px;
  height: 100px;
  background-color: rgb(199, 199, 199);
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.chat-item-right {
  display: flex;
  justify-content: flex-end;
  width: 80%;
  float: right;
  margin-top: 5px;
  margin-right: 5px;
  margin-bottom: 5px;
  .chat-item-img {
    border-radius: 50px;
    width: 50px;
    height: 50px;
  }
  span {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #50abff;
    border-radius: 10px;
    padding: 0px 10px;
    margin-right: 10px;
    color: #ffffff;
    font-size: 16px;
  }
}
.chat-item-left {
  display: flex;
  justify-content: flex-start;
  width: 80%;
  float: left;
  margin-top: 5px;
  margin-left: 5px;
  margin-bottom: 5px;
  .chat-item-img {
    border-radius: 50px;
    width: 50px;
    height: 50px;
  }
  span {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: white;
    border-radius: 10px;
    padding: 5px 10px;
    margin-left: 10px;
    color: black;
    font-size: 16px;
  }
}
.chat-input-container {
  position: absolute;
  bottom: 0;
  width: 100wh;
  display: flex;
  align-items: center;
  /* border: 1px solid #ccc; */
  border-radius: 5px;
  background-color: #f4f4f4;
  padding: 5px;
}

.chat-input {
  flex: 1;
  border: none;
  outline: none;
  padding: 5px 10px;
  font-size: 16px;
}

.microphone-btn,
.smile-btn {
  border: none;
  background-color: transparent;
  padding: 5px;
  cursor: pointer;
  outline: none;
}

.microphone-btn img,
.smile-btn img {
  width: 24px;
  height: 24px;
}
.send-btn {
  font-size: 18px;
  cursor: pointer;
}
.microphone-btn:hover,
.smile-btn:hover {
  background-color: #f0f0f0;
}
</style>
